<template>
  <view class="login-panel">
    <view class="icon-logo">
      <image class="img" src="@/static/images/icon-logo.jpg"></image>
    </view>
    <view class="tips"
      >本小程序为隐耀家具服务有限公司内部专属应用，仅面向公司内部成员开放。需要登录后方可访问本小程序。请使用已备案的账号及对应密码完成登录，如有疑问或登录异常，请及时联系内部
      IT 支持人员协助处理。</view
    >
    <view class="form">
      <u--form
        labelPosition="left"
        :model="loginform"
        :rules="rules"
        ref="uForm"
      >
        <u-form-item label="账号" prop="userAccount" borderBottom ref="item1">
          <u--input
            prefixIcon="account"
            v-model="loginform.userAccount"
            placeholder="请输入账号"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item label="密码" prop="password" borderBottom ref="item1">
          <u--input
            prefixIcon="lock"
            v-model="loginform.password"
            placeholder="请输入密码"
            type="password"
            :password="false"
            border="none"
          ></u--input>
        </u-form-item>
      </u--form>
    </view>

    <u-button
      color="#a22d27"
      :plain="true"
      :customStyle="btnLoginStyle"
      @click="authLogin"
    >
      <view style="font-size: 30rpx; display: flex; align-items: center"
        >账号登录</view
      >
    </u-button>
    <u-button
      color="#a22d27"
      openType="getPhoneNumber"
      :customStyle="btnLoginStyle"
      @getphonenumber="fetchUserPhoneInfo"
    >
      <view style="font-size: 30rpx; display: flex; align-items: center"
        ><u-icon name="phone-fill" color="#ffffff" size="18"></u-icon
        >手机号快捷登录</view
      >
    </u-button>
    <!-- <u-button color="#05d380" @click="test">
			<view style="font-size: 32rpx;">test</view>
		</u-button> -->

    <!-- 隐私协议 -->
    <!-- #ifdef MP-WEIXIN -->
    <!-- <privacy-popup ref="privacyComponent"></privacy-popup> -->
    <!-- #endif -->
  </view>
</template>

<script>
import { wxMiniLogin, getUserInfoApi, accountLogin } from "@/api/user/index";
import Md5 from "@/uni_modules/wht-md5/js_sdk/wht-md5.js";
export default {
  data() {
    return {
      loginCode: "",
      btnLoginStyle: {
        width: "600rpx",
        marginTop: "40rpx",
      },
      loginform: {
        userAccount: "",
        password: "",
      },
      rules: {
        userAccount: {
          type: "string",
          required: true,
          message: "请填写账号",
          trigger: ["blur", "change"],
        },
        password: {
          type: "string",
          required: true,
          message: "请输入密码",
          trigger: ["blur", "change"],
        },
      },
      callback: false,
      isRoot: false,
      redirect: "",
    };
  },
  beforeDestroy() {
    if (!this.callback && !this.isRoot) {
      // const eventChannel = this.getOpenerEventChannel();
      // eventChannel.emit('loginCompletion', null);
    }
  },
  onUnload() {},
  onLoad(options) {
    const pages = getCurrentPages();
    if (pages) {
      if (pages.length == 1) {
        this.isRoot = true;
        if (this.$store.state.token && this.$store.state.token.length) {
          uni.reLaunch({
            url: "/pages/home/index",
          });
          return;
        }
      }
    }

    var that = this;
    // uni.login({
    // 	success: res => {
    // 		that.loginCode = res.code || ''
    // 	}
    // })

    if (options && options.redirect) {
      this.redirect = options.redirect || "";
      // console.log("########", this.redirect)
    }
  },
  methods: {
    /**
     * 账号登录
     */
    authLogin() {
      var that = this;
      let data = {
        ...this.loginform,
        password: Md5(this.loginform.password, { uppercase: true }),
      };
      accountLogin.request(data).then((res) => {
        that.beforeLogin(res);
      }).catch((err) => {
        console.log(err, 'err');
        
        uni.showToast({
          icon: "none",
          title: err.data.detail || "登录失败，请稍后重试",
        });
      })
    },
    test() {
      const hashUpper = Md5("123456", { uppercase: true });
    },
    /**
     * 登录后操作
     * @param res 登录返回的数据
     */
    beforeLogin(res) {
      let that = this;
      // console.log(res, 'wxMiniLogin');
      uni.hideLoading();
      if (typeof res.data === "object") {
        var tokenobj = res.data;
        let userinfo = {};
        that.$store.dispatch("setToken", tokenobj.access_token);
        that.$store.dispatch("setRefresh_token", tokenobj.refresh_token);
        uni.setStorageSync("token", tokenobj.access_token);
        uni.setStorageSync("refresh_token", tokenobj.refresh_token);
        getUserInfoApi()
          .then((response) => {
            userinfo = response.data;
            userinfo.nickname = userinfo.realName;
            userinfo.mobile = userinfo.phoneNumber;
            userinfo.mobile_encrypt = `${userinfo.phoneNumber?.substr(
              0,
              3
            )}****${userinfo.phoneNumber.substr(7)}`;
            console.log(userinfo, "userinfo");
            that.$store.dispatch("setUserInfo", userinfo);
            uni.setStorageSync("userInfo", JSON.stringify(userinfo));

            // return
            if (that.isRoot) {
              if (that.redirect && that.redirect.length) {
                let redirect = that.redirect;
                if (redirect.indexOf("%") > -1) {
                  redirect = decodeURIComponent(redirect);
                }

                uni.reLaunch({
                  url: redirect,
                });
              } else {
                uni.reLaunch({
                  url: "/pages/welcome/index",
                });
              }
            } else {
              // that.callback = true
              // const eventChannel = that.getOpenerEventChannel();
              // eventChannel.emit('loginCompletion', userinfo);
              if (that.redirect && that.redirect.length) {
                let redirect = that.redirect;
                if (redirect.indexOf("%") > -1) {
                  redirect = decodeURIComponent(redirect);
                }

                uni.redirectTo({
                  url: redirect,
                });
              } else {
                uni.navigateBack();
              }
            }
          })
          .catch((e) => {
            console.log(e);
            uni.showModal({
              title: "提示",
              content: "登录失败，请重新点击并授权!",
              showCancel: false,
            });
          });

        // try {
        // 	tokenobj.mobile_encrypt =
        // 		`${tokenobj.mobile.substr(0, 3)}****${tokenobj.mobile.substr(7)}`
        // } catch (_) {
        // 	tokenobj.mobile_encrypt = tokenobj.mobile
        // }
      } else {
        // 解密失败
        uni.showModal({
          title: "提示",
          content: "登录失败，请重新点击并授权!",
          showCancel: false,
        });
      }
    },
    /**
     * 登录
     */
    login(params) {
      var that = this;
      wxMiniLogin
        .request(params)
        .then((res) => {
          that.beforeLogin(res);
        })
        .catch((err) => {
          uni.hideLoading();
        });
    },
    // 获取用户手机号信息
    fetchUserPhoneInfo(phoneInfoRes) {
      // console.log(phoneInfoRes, 'phoneInfoRes');
      // return

      // 用户主动拒绝授权
      if (phoneInfoRes.detail.errMsg.indexOf("user deny") != -1) {
        uni.showModal({
          title: "登录失败",
          content: "需要通过授权才能继续，请重新点击并授权!",
          showCancel: false,
        });
        return;
      }

      if (phoneInfoRes.detail.errMsg.indexOf("no permission") != -1) {
        uni.showModal({
          title: "登录失败",
          content: phoneInfoRes.detail.errMsg || "",
          showCancel: false,
        });
        return;
      }

      // 微信号没有登记手机号码
      if (!phoneInfoRes.detail.iv) {
        uni.showModal({
          title: "登录失败",
          content: "获取手机号码失败",
          showCancel: false,
        });
        return;
      }

      uni.showLoading({
        title: "登录中",
        mask: true,
      });
      // console.log(this.loginCode);
      // console.log(this.loginCode.length);
      // return
      if (this.loginCode && this.loginCode.length) {
        let params = {
          code: this.loginCode,
          iv: phoneInfoRes.detail.iv,
          encryptedData: phoneInfoRes.detail.encryptedData,
        };
        // console.log(8848);
        this.login(params);
      } else {
        var that = this;
        uni.login({
          success: (res) => {
            // console.log(res, 'uni.login');
            let code = res.code || "";
            // let params = {
            // 	code: code,
            // 	iv: phoneInfoRes.detail.iv,
            // 	encryptedData: phoneInfoRes.detail.encryptedData
            // }
            let params = {};
            uni.getUserInfo({
              success: function (responent) {
                // var userInfo = res.userInfo
                // console.log(res, 'userInfo');
                params = {
                  jsCode: code,
                  rawData: responent.rawData,
                  encryptedData: responent.encryptedData,
                  iv: responent.iv,
                  signature: responent.signature,
                  phoneCode: phoneInfoRes.detail.code,
                };
                console.log(params);

                that.login(params);
              },
              fail(e) {
                console.log(e);
              },
            });
            // that.login(params)
          },
          fail: (err) => {
            uni.hideLoading();
            uni.showModal({
              title: "提示",
              content: "登录失败，请重新点击并授权!",
              showCancel: false,
            });
          },
        });
      }
    },
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.uForm.setRules(this.rules);
  },
};
</script>

<style lang="scss" scoped>
.login-panel {
  padding: 0 80rpx;
  display: flex;
  flex-direction: column;
  align-items: center;

  .icon-logo {
    .img {
      width: 100rpx;
      height: 100rpx;
      border-radius: 160rpx;
    }
  }

  .title {
    font-size: 46rpx;
    margin-top: 40rpx;
  }

  .tips {
    font-size: 24rpx;
    margin-top: 40rpx;
    color: #aaaaaa;
    line-height: 1.5rem;
  }

  .phone-panel-container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;

    .phone-panel {
      width: 520rpx;
      background-color: #fff;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 40rpx 20rpx;
      // margin-bottom: 100rpx;
      border-radius: 20rpx;

      .phone-panel-tips {
        font-size: 40rpx;
      }

      .phone-panel-remark {
        margin-top: 20rpx;
        color: #909399;
      }
    }
  }
}
.form {
  width: 100%;
  margin-top: 40rpx;
  margin-bottom: 40rpx;
}
</style>
